;!function(window) {
    "use strict";

    var index = 0, MusePop = function (options) {
        var _this = this;
        _this.config = ready.extend(options);

        if (_this.config.show) {
            _this.config.show();
        }

        _this.build();
        
        if (_this.config.shown) {
            _this.config.shown();
        }
    };

    var config = {
        type: 'alert',    // alert/page/load
        modal: true,                // 显示遮罩
        backdrop: true,             // 点击遮罩关闭
        fixed: true,
        animate: 'scale',

        // 弹层显示前
        show: function() {
        },

        // 弹层显示后
        shown: function() {
        },

        showCancel : true,
        cancelText : '关闭',
        cancel : function (index) {
            muses.close(index);
        },

        showAdditional : false,
        additionalText : '其他',
        additional : function (index) {},

        showOk  : true,
        okText  : '确定',
        ok : function (index) {
            muses.close(index);
        }
    };

    var ready = {
        extend: function (obj) {
            var option = JSON.parse(JSON.stringify(config));
            for (var i in obj) {
                if (!obj.hasOwnProperty(i)) continue;
                option[i] = obj[i];
            }
            return option;
        },
        timer: {},
        end: {}
    };

    ready.touch = function (elem, fn) {
        elem.addEventListener('click', function (e) {
            fn.call(this, e);
        }, false);
    };
    
    MusePop.prototype = {
        build: function () {
            var _this = this, config = _this.config, musepopbox = document.createElement('div');

            // build container div
            _this.id = musepopbox.id = 'muse-popup-container-' + index;
            musepopbox.setAttribute('class', 'muse-popup-container ' + 'muse-popup-container-' + (config.type || 0));
            musepopbox.setAttribute('index', index);

            // build popup title if have
            var title = (function () {
                var title_type = typeof config.title === 'object';
                var title_close_button = '<button class="close" data-dismiss="modal" type="button"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>';
                return config.title
                    ? '<div class="muse-popup-header">' + config.title + title_close_button + '</div>'
                    : '';
            }());

            // build buttons
            var button = (function () {
                var buttonDOM = '';
                if (config.showCancel && config.type === 'alert') {
                    buttonDOM += '<span type="cancel">' + config.cancelText + '</span>';
                }
                if (config.showAdditional) {
                    buttonDOM += '<span type="additional">' + config.additionalText + '</span>';
                }
                if (config.showOk && config.type === 'alert') {
                    buttonDOM += '<span type="ok">' + config.okText + '</span>';
                }

                if (buttonDOM.length > 0) {
                    config.hasButtons = true;
                    return '<div class="muse-popup-buttons">' + buttonDOM + '</div>';
                } else {
                    return '';
                }
            }());

            if (!config.fixed) {
                config.top = config.hasOwnProperty('top') ? config.top : 100;
                config.style = config.style || '';
                config.style += ' top:' + (document.body.scrollTop + config.top) + 'px';
            }

            // if load
            if (config.type === 'load') {
                config.content = '<i></i><i class="muse-popup-load"></i><i></i><p>' + (config.content || '') + '</p>';
            }

            if (config.type === 'footer' || config.type === 'message') {
                config.animate = 'up';
            }

            if (config.type === 'message') {
                config.modal = false;
            }

            musepopbox.innerHTML = (config.modal ? '<div '
                                + (typeof config.modal === 'string' ? 'style="' + config.modal + '"' : '')
                                + ' class="muse-popup-modal"></div>' : '')
                +'<div class="muse-popup-main" ' + (!config.fixed ? 'style="position:static;"' : '') +'>'
                +    '<div class="muse-popup-section">'
                +         '<div class="muse-popup-child muse-popup-' + config.type
                +            (config.className ? config.className : '') + ' '
                +            (config.animate ? 'muse-popup-animate-' + config.animate : '') + '" '
                +            (config.style ? 'style="' + config.style + '"' : '') + '>'
                +         title
                +            '<div class="muse-popup-content">' + config.content + '</div>'
                +         button
                +        '</div>'
                +    '</div>'
                +'</div>';

            // maintain only one
            if (!config.type || config.type === 'load') {
                var dialogs = document.getElementsByClassName('muse-popup-container' + config.type),
                    dialogsLength = dialogs.length;
                if (dialogsLength >= 1) {
                    muses.close(dialogs[0].getAttribute('index'));
                }
            }

            document.body.appendChild(musepopbox);
            var elem = _this.elem = document.querySelectorAll('#' + _this.id)[0];
            config.success && config.success(elem);

            _this.index = index++;
            _this.action(config, elem);
        },
        // action register
        action: function (config, elem) {
            var _this = this;

            // time(seconds) to auto close
            if (config.time) {
                ready.timer[_this.index] = setTimeout(function () {
                    muses.close(_this.index);
                }, config.time * 1000);
            }

            // btn action
            var btn = function () {
                var type = this.getAttribute('type');
                if (type === 'cancel') {
                    config.cancel && config.cancel();
                    muses.close(_this.index);
                } else if (type === 'additional') {
                    config.additional && config.additional(_this.index);
                } else if (type === 'ok') {
                    config.ok && config.ok(_this.index);
                    muses.close(_this.index);
                }
            };

            if (config.hasButtons) {
                var buttons = elem.getElementsByClassName('muse-popup-buttons')[0].children,
                    buttonsLength = buttons.length;
                for (var i = 0; i < buttonsLength; i++) {
                    ready.touch(buttons[i], btn);
                }
            }

            // 头部 x 按钮
            $('.muse-popup-header button.close').click(function() {
                muses.close(_this.index);
            });

            // modal click to close
            if (config.modal && config.backdrop) {
                var modal = elem.getElementsByClassName('muse-popup-modal')[0];
                ready.touch(modal, function () {
                    muses.close(_this.index, config.end);
                });
            }

            config.end && (ready.end[_this.index] = config.end);
        }
    };

    var muses = {
        version: '1.0',
        index: index,

        open: function(options) {
            var o = new MusePop(options || {});
            return o.index;
        },

        close: function(index) {
            var box = document.querySelectorAll('#muse-popup-container-' + index)[0];
            if(!box) return;
            box.innerHTML = '';
            document.body.removeChild(box);
            clearTimeout(ready.timer[index]);
            delete ready.timer[index];
            typeof ready.end[index] === 'function' && ready.end[index]();
            delete ready.end[index];
        },

        closeAll: function(){
            var boxes = document.getElementsByClassName('muse-popup-container');
            for(var i = 0, len = boxes.length; i < len; i++){
                muses.close((boxes[0].getAttribute('index')|0));
            }
        }
    };

    window.muses = muses;
}(window);